package com.power.sifa.std.dao.impl;

import com.plf.core.common.dao.OffersetTransformers;
import com.power.sifa.std.dao.Std_admuserDaoCustom;
import com.power.sifa.std.model.pageInfo.Std_admuserPageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 行政管理单位关联赣政通人员表 持久层实现(hibernate)
 */

@Repository
@Slf4j
public class Std_admuserDaoImpl implements Std_admuserDaoCustom {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private EntityManager entityManager;


    @Override
    public List<Map<String, Object>> listDetail(Std_admuserPageInfo pageInfo) {

        List<Map<String, Object>> result = new ArrayList<>();
        StringBuffer sql = new StringBuffer("  select sa.id, sa.mobile, sa.unitid, sa.userid, sa.username, sa.admunitid, sa.address, dd.orgname as orgname from std_admuser sa left join di_dept dd on sa.unitid = dd.id where 1 = 1  ");

        List<Object> paramsList = new ArrayList<>();
        int index = 1;

        // 社矫人员
        if (StringUtils.isNotEmpty(pageInfo.getF_username())) {
            sql.append(" and sa.username like  ?" + index++);
            paramsList.add("%" + pageInfo.getF_username() +"%");
        }
        if (StringUtils.isNotEmpty(pageInfo.getF_mobile())) {
            sql.append(" and sa.mobile = ?" + index++);
            paramsList.add(pageInfo.getF_mobile());
        }

        if (StringUtils.isNotEmpty(pageInfo.getF_admunitid())) {
            sql.append(" and sa.admunitid = ?" + index++);
            paramsList.add(pageInfo.getF_admunitid());
        }

        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
        log.info(sql.toString());

        // 添加条件
        for (int i = 0; i <= paramsList.size() - 1; i++) {
            query.setParameter(i + 1, paramsList.get(i));
        }
        // 查询总数
        pageInfo.setAllcount(query.getResultList().size());
        // 分页
        if (pageInfo.getAllcount() > 0) {
            int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
            result = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
        }
        return result;
    }

}